package mx.gob.imss.reiman.clientes.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ResourceBundle;

import mx.gob.imss.reiman.clientes.service.ArchivoService;

import org.apache.commons.io.FilenameUtils;
import org.primefaces.model.UploadedFile;
import org.springframework.stereotype.Service;

/**
 * 
 * @author Alberto Dzul Calvillo
 * @version 1.0
 * 
 */
@Service("archivoService")
public class ArchivoServiceImpl implements Serializable, ArchivoService {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -3335522206077457294L;
	private final ResourceBundle conf = ResourceBundle.getBundle("mx.gob.imss.reiman.clientes.i18n.configuration_es_MX");
	private final String uploadDirectory = conf.getString("uploadDirectory");
	
	public String guarda(UploadedFile file) throws IOException {
		String archivo = FilenameUtils.getBaseName(file.getFileName()) +"."+ FilenameUtils.getExtension(file.getFileName());
		String name = uploadDirectory + archivo;
		FileOutputStream fos = new FileOutputStream(new File(name));
		InputStream is = file.getInputstream();
		int BUFFER_SIZE = 8192;
		byte[] buffer = new byte[BUFFER_SIZE];
		int a;
		while (true) {
			a = is.read(buffer);
			if (a < 0)
				break;
			fos.write(buffer, 0, a);
			fos.flush();
		}
		fos.close();
		is.close();
		return name;
	}
}